<template>
  <Layout>
    <div class="content-header">
      <h2>机器信息</h2>
    </div>
    <div class="content-body">
      <!-- 加载状态 -->
      <div v-if="loading" style="text-align: center; padding: 40px; font-size: 16px; color: var(--text-secondary)">
        加载中...
      </div>

      <!-- 错误提示 -->
      <div v-if="error" style="text-align: center; padding: 40px; font-size: 16px; color: var(--danger-color)">
        {{ error }}
      </div>

      <!-- 数据展示 -->
      <template v-if="!loading && !error">
        <el-card class="stat-cards">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card info">
                <div>
                  <div class="stat-label">总机器数</div>
                  <div class="stat-value">{{ totalMachines }} 台</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card success">
                <div>
                  <div class="stat-label">在线机器</div>
                  <div class="stat-value">{{ onlineMachines }} 台</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card warning">
                <div>
                  <div class="stat-label">告警机器</div>
                  <div class="stat-value">{{ warningMachines }} 台</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card danger">
                <div>
                  <div class="stat-label">离线机器</div>
                  <div class="stat-value">{{ offlineMachines }} 台</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>服务器列表</span>
            </div>
          </template>
          
          <div class="table-toolbar">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-select 
                  v-model="filters.status"
                  placeholder="请选择状态"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="全部" value="all" />
                  <el-option label="在线" value="online" />
                  <el-option label="告警" value="warning" />
                  <el-option label="离线" value="offline" />
                </el-select>
              </el-col>
              
              <el-col :span="12">
                <el-input 
                  v-model="filters.search"
                  placeholder="输入服务器名称、IP、系统、用途或负责人"
                  clearable
                />
              </el-col>
              
              <el-col :span="4">
                <el-button @click="clearFilters">清除筛选</el-button>
              </el-col>
            </el-row>
          </div>

          <el-table 
            :data="paginatedMachines" 
            style="width: 100%" 
            :default-sort="{ prop: 'name', order: 'ascending' }"
          >
            <el-table-column 
              prop="name" 
              label="服务器名称" 
              sortable 
              :sort-method="(a, b) => a.name.localeCompare(b.name)"
            >
              <template #default="scope">
                <el-link 
                  type="primary" 
                  @click="openDetail(scope.row)"
                >
                  {{ scope.row.name }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="ip" label="IP地址" />
            <el-table-column 
              prop="os" 
              label="操作系统" 
              sortable 
              :sort-method="(a, b) => a.os.localeCompare(b.os)"
            />
            <el-table-column 
              prop="purpose" 
              label="用途" 
              sortable 
              :sort-method="(a, b) => a.purpose.localeCompare(b.purpose)"
            >
              <template #default="scope">
                <span style="font-weight: 600; color: var(--primary-light)">
                  {{ scope.row.purpose }}
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="owner" 
              label="负责人" 
              sortable 
              :sort-method="(a, b) => a.owner.localeCompare(b.owner)"
            >
              <template #default="scope">
                <span style="font-weight: 500; color: var(--text-primary)">
                  {{ scope.row.owner }}
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="cpu" 
              label="CPU使用率" 
              sortable 
              :sort-method="(a, b) => a.cpu - b.cpu"
            >
              <template #default="scope">
                <span :style="{ color: getUsageColor(scope.row.cpu), fontWeight: 600 }">
                  {{ scope.row.cpu }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="memory" 
              label="内存使用率" 
              sortable 
              :sort-method="(a, b) => a.memory - b.memory"
            >
              <template #default="scope">
                <span :style="{ color: getUsageColor(scope.row.memory), fontWeight: 600 }">
                  {{ scope.row.memory }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="disk" 
              label="磁盘使用率" 
              sortable 
              :sort-method="(a, b) => a.disk - b.disk"
            >
              <template #default="scope">
                <span :style="{ color: getUsageColor(scope.row.disk), fontWeight: 600 }">
                  {{ scope.row.disk }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="status" 
              label="状态" 
              sortable 
              :sort-method="(a, b) => a.status.localeCompare(b.status)"
            >
              <template #default="scope">
                <el-tag 
                  :type="scope.row.status === 'online' ? 'success' : scope.row.status === 'warning' ? 'warning' : 'danger'"
                >
                  {{ scope.row.status === 'online' ? '在线' : scope.row.status === 'offline' ? '离线' : '告警' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        <!-- 分页组件 -->
        <Pagination
          :current-page="currentPage"
          :total-pages="totalPages"
          :page-size="pageSize"
          :total-items="filteredMachines.length"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />         
      </el-card>
      </template>
    </div>

    <!-- 服务器详情弹窗 -->
    <el-dialog
      v-model="showDetail"
      title="服务器详情"
      width="90%"
      top="30px"
      :before-close="closeDetail"
      style="z-index: 2000"
    >
      <div v-if="selectedMachine" class="detail-layout">
        <el-row :gutter="20">
          <!-- 左侧区域 -->
          <el-col :span="12">
            <!-- 基本信息 -->
            <el-card class="detail-card">
              <template #header>
                <div class="card-header">
                  <span>基本信息</span>
                </div>
              </template>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="服务器名称">{{ selectedMachine.name }}</el-descriptions-item>
                <el-descriptions-item label="IP地址">{{ selectedMachine.ip }}</el-descriptions-item>
                <el-descriptions-item label="操作系统">{{ selectedMachine.os }}</el-descriptions-item>
                <el-descriptions-item label="用途">{{ selectedMachine.purpose }}</el-descriptions-item>
                <el-descriptions-item label="负责人">{{ selectedMachine.owner }}</el-descriptions-item>
                <el-descriptions-item label="机房位置">{{ selectedMachine.location }}</el-descriptions-item>
                <el-descriptions-item label="运行时长">{{ selectedMachine.uptime }}</el-descriptions-item>
                <el-descriptions-item label="最后重启">{{ selectedMachine.lastReboot }}</el-descriptions-item>
              </el-descriptions>
            </el-card>

            <!-- 资源使用率 -->
            <el-card class="detail-card" style="margin-top: 20px;">
              <template #header>
                <div class="card-header">
                  <span>资源使用率</span>
                </div>
              </template>
              <div class="resource-grid">
                <div class="resource-item">
                  <div class="resource-header">
                    <span class="resource-label">CPU</span>
                    <span class="resource-value" :style="{ color: getUsageColor(selectedMachine.cpu) }">
                      {{ selectedMachine.cpu }}%
                    </span>
                  </div>
                  <el-progress 
                    :percentage="selectedMachine.cpu" 
                    :stroke-width="18"
                    :color="getUsageColor(selectedMachine.cpu)"
                  />
                </div>

                <div class="resource-item">
                  <div class="resource-header">
                    <span class="resource-label">内存</span>
                    <span class="resource-value" :style="{ color: getUsageColor(selectedMachine.memory) }">
                      {{ selectedMachine.memory }}%
                    </span>
                  </div>
                  <el-progress 
                    :percentage="selectedMachine.memory" 
                    :stroke-width="18"
                    :color="getUsageColor(selectedMachine.memory)"
                  />
                </div>

                <div class="resource-item">
                  <div class="resource-header">
                    <span class="resource-label">磁盘</span>
                    <span class="resource-value" :style="{ color: getUsageColor(selectedMachine.disk) }">
                      {{ selectedMachine.disk }}%
                    </span>
                  </div>
                  <el-progress 
                    :percentage="selectedMachine.disk" 
                    :stroke-width="18"
                    :color="getUsageColor(selectedMachine.disk)"
                  />
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧区域 - 运行进程 -->
          <el-col :span="12">
            <el-card class="detail-card">
              <template #header>
                <div class="card-header">
                  <span>运行进程</span>
                </div>
              </template>
              <el-table 
                :data="selectedMachine.processes || []" 
                style="width: 100%" 
                max-height="500"
              >
                <el-table-column prop="name" label="进程名称" />
                <el-table-column prop="pid" label="PID" width="100" />
                <el-table-column prop="user" label="用户" />
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === 'running' ? 'success' : 'info'">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="port" label="端口" />
                <el-table-column prop="cpu" label="CPU使用率(%)">
                  <template #default="scope">
                    <span :style="{ color: getUsageColor(scope.row.cpu) }">
                      {{ scope.row.cpu }}%
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="memory" label="内存(MB)" />
              </el-table>
              <div v-if="!selectedMachine.processes || selectedMachine.processes.length === 0" class="no-processes">
                暂无运行进程
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </Layout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import Layout from '../components/Layout.vue'
import Pagination from '../components/Pagination.vue'
import { machineAPI } from '../services/api'
import { getUsageColor, getStatusClass } from '../utils'
import { useTableData } from '../composables/useTableData'
import type { Machine } from '../types'

const machinesData = ref<Machine[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const sortConfig = ref<{ key: string | null; direction: 'asc' | 'desc' }>({
  key: null,
  direction: 'asc'
})
const filters = ref({
  status: 'all',
  search: ''
})
const selectedMachine = ref<Machine | null>(null)
const showDetail = ref(false)

// 使用统一的分页逻辑
const {
  currentPage,
  pageSize,
  paginatedData: paginatedMachines,
  totalPages,
  handlePageChange,
  handlePageSizeChange
} = useTableData({
  data: machinesData,
  filters,
  defaultSort: { key: null, direction: 'asc' }, 
  pageSize: 5
})

// 加载数据
const fetchMachines = async () => {
  try {
    loading.value = true
    const response: any = await machineAPI.getAll()
    if (response.success) {
      machinesData.value = response.data || []
    } else {
      error.value = '加载数据失败: ' + response.message
    }
    error.value = null
  } catch (err: any) {
    error.value = '加载数据失败: ' + err.message
    console.error('Failed to fetch machines:', err)
  } finally {
    loading.value = false
  }
}

// 排序处理
const handleSort = (key: string) => {
  let direction: 'asc' | 'desc' = 'asc'
  if (sortConfig.value.key === key && sortConfig.value.direction === 'asc') {
    direction = 'desc'
  }
  sortConfig.value = { key, direction }
}

// 筛选和排序后的数据
const filteredMachines = computed(() => {
  let filtered = [...machinesData.value]

  // 状态筛选
  if (filters.value.status !== 'all') {
    filtered = filtered.filter(m => m.status === filters.value.status)
  }

  // 搜索筛选
  if (filters.value.search) {
    const searchLower = filters.value.search.toLowerCase()
    filtered = filtered.filter(m => 
      m.name.toLowerCase().includes(searchLower) ||
      m.ip.includes(searchLower) ||
      m.os.toLowerCase().includes(searchLower) ||
      m.purpose.toLowerCase().includes(searchLower) ||
      m.owner.toLowerCase().includes(searchLower)
    )
  }

  // 排序
  if (sortConfig.value.key) {
    filtered.sort((a, b) => {
      const aVal = a[sortConfig.value.key as keyof Machine]
      const bVal = b[sortConfig.value.key as keyof Machine]
      
      if (aVal < bVal) return sortConfig.value.direction === 'asc' ? -1 : 1
      if (aVal > bVal) return sortConfig.value.direction === 'asc' ? 1 : -1
      return 0
    })
  }

  return filtered
})

// 统计数据
const totalMachines = computed(() => machinesData.value.length)
const onlineMachines = computed(() => machinesData.value.filter(m => m.status === 'online').length)
const warningMachines = computed(() => machinesData.value.filter(m => m.status === 'warning').length)
const offlineMachines = computed(() => machinesData.value.filter(m => m.status === 'offline').length)

// 所有用途类型
const allPurposes = computed(() => [...new Set(machinesData.value.map(m => m.purpose))])

// 工具函数
const getSortClass = (key: string) => {
  if (sortConfig.value.key !== key) return 'sortable'
  return `sortable ${sortConfig.value.direction}`
}

const clearFilters = () => {
  filters.value = { status: 'all', search: '' }
  sortConfig.value = { key: null, direction: 'asc' }
  currentPage.value = 1
}

// 详情弹窗
const openDetail = (machine: Machine) => {
  selectedMachine.value = machine
  showDetail.value = true
}

const closeDetail = () => {
  showDetail.value = false
  setTimeout(() => { selectedMachine.value = null }, 300)
}

// 当筛选条件改变时，重置到第一页
const resetPageOnFilterChange = () => {
  currentPage.value = 1
}

// 使用watch监听筛选条件变化
watch([filters, sortConfig], () => {
  resetPageOnFilterChange()
})

onMounted(() => {
  fetchMachines()
})
</script>
